<template>
  <div class="file-upload-container">
    <div class="file-wrapper" @click.prevent="triggerUpload">
      <slot name="loading" v-if="uploadState === 'loading'">
        <button class="btn btn-primary" disabled>正在上传...</button>
      </slot>

      <slot
        v-else-if="uploadState === 'success'"
        name="uploaded"
        :uploadedData="uploadedData"
      >
        <button class="btn btn-primary" disabled>上传成功</button>
      </slot>

      <slot v-else name="default">
        <span class="btn btn-primary">点击上传</span>
      </slot>
    </div>
    <input
      type="file"
      class="file-input d-none"
      ref="fileInput"
      @change="handleFileChange"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, ref } from 'vue'
import axios from 'axios'
export type UploadStatus = 'ready' | 'loading' | 'success' | 'error'
type FuncCheck = (file: File) => Boolean
export default defineComponent({
  props: {
    action: {
      type: String as PropType<string>
    },
    beforeUpload: {
      type: Function as PropType<FuncCheck>
    }
  },
  setup(props, context) {
    const uploadState = ref<UploadStatus>('ready')
    const fileInput = ref<null | HTMLInputElement>(null)
    const uploadedData = ref<any>()

    const triggerUpload = () => {
      if (fileInput.value) {
        fileInput.value.click()
      }
    }

    const handleFileChange = (e: Event) => {
      const currentTarget = e.target as HTMLInputElement
      if (currentTarget.files) {
        const files = currentTarget.files
        if (props.beforeUpload) {
          const result = props.beforeUpload(files[0])
          if (!result) return
        }
        uploadState.value = 'loading'
        // 上传过程
        console.log(files[0], 'files----files')
        const formData = new FormData()
        formData.append('file', files[0])
        axios
          .post((props as any).action, formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then((response) => {
            console.log('response...:', response)
            uploadState.value = 'success'
            uploadedData.value = response.data
            context.emit('file-uploaded', response.data)
          })
          .catch((error) => {
            uploadState.value = 'error'
            context.emit('file-uploaded-error', error)
          })
          .finally(() => {
            // uploadState.value = 'ready';
            if (fileInput.value) {
              fileInput.value.value = ''
            }
          })
      }
    }

    return {
      triggerUpload,
      fileInput,
      uploadState,
      handleFileChange,
      uploadedData
    }
  }
})
</script>
